<template>
  <div class="patient-management">
    <div class="page-header">
      <h1 class="page-title">患者管理</h1>
      <div class="header-actions">
        <!-- <el-button type="primary" :icon="Plus" @click="showAddDialog = true">
          新增患者
        </el-button>
        <el-button :icon="Download" @click="exportPatients">
          导出数据
        </el-button> -->
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="never">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="searchQuery"
            placeholder="搜索患者姓名、电话或身份证"
            :prefix-icon="Search"
            clearable
            @input="handleSearch"
          />
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="filterStatus"
            placeholder="患者状态"
            clearable
            @change="handleFilter"
          >
            <el-option label="正常" value="正常" />
            <el-option label="住院" value="住院" />
            <el-option label="出院" value="出院" />
            <el-option label="死亡" value="死亡" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="filterGender"
            placeholder="性别"
            clearable
            @change="handleFilter"
          >
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-col>
        <el-col :span="8">
          <div class="stats-info">
            <span class="stat-item"
              >总患者: <strong>{{ patientStats.total }}</strong></span
            >
            <span class="stat-item"
              >平均年龄: <strong>{{ patientStats.averageAge }}岁</strong></span
            >
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 患者列表 -->
    <el-card shadow="never">
      <el-table
        :data="filteredPatients"
        v-loading="loading"
        stripe
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="患者编号" width="100" />
        <el-table-column prop="name" label="姓名" width="100">
          <template #default="{ row }">
            <el-button type="text" @click="handleViewDetail(row)">
              {{ row.name }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="60">
          <template #default="{ row }">
            <el-tag
              :type="row.gender === '男' ? 'primary' : 'success'"
              size="small"
            >
              {{ row.gender }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="60" />
        <el-table-column prop="phone" label="联系电话" width="130" />
        <el-table-column prop="bloodType" label="血型" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastVisit" label="最近就诊" width="110" />
        <el-table-column prop="diagnoses" label="主要诊断" min-width="150">
          <template #default="{ row }">
            <el-tag
              v-for="diagnosis in row.diagnoses.slice(0, 2)"
              :key="diagnosis"
              size="small"
              class="diagnosis-tag"
            >
              {{ diagnosis }}
            </el-tag>
            <span v-if="row.diagnoses.length > 2" class="more-diagnoses">
              +{{ row.diagnoses.length - 2 }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="text" size="small" @click="handleViewHistory(row)">
              病历
            </el-button>
            <el-button type="text" size="small" @click="handleAppointment(row)">
              预约
            </el-button>
            <el-dropdown
              @command="(command: string) => handleMoreActions(command, row)"
            >
              <el-button type="text" size="small">
                更多<el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    command="delete"
                    :disabled="row.status === '住院'"
                  >
                    删除
                  </el-dropdown-item>
                  <el-dropdown-item command="archive"> 归档 </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredPatients.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑患者对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingPatient ? '编辑患者' : '新增患者'"
      width="800px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="patientForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input
                v-model="patientForm.name"
                placeholder="请输入患者姓名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="patientForm.gender">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number
                v-model="patientForm.age"
                :min="0"
                :max="150"
                placeholder="年龄"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="血型" prop="bloodType">
              <el-select
                v-model="patientForm.bloodType"
                placeholder="请选择血型"
              >
                <el-option label="A型" value="A型" />
                <el-option label="B型" value="B型" />
                <el-option label="AB型" value="AB型" />
                <el-option label="O型" value="O型" />
                <el-option label="未知" value="未知" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input
                v-model="patientForm.phone"
                placeholder="请输入联系电话"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input
                v-model="patientForm.idCard"
                placeholder="请输入身份证号"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身高(cm)" prop="height">
              <el-input-number
                v-model="patientForm.height"
                :min="50"
                :max="250"
                placeholder="身高"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="体重(kg)" prop="weight">
              <el-input-number
                v-model="patientForm.weight"
                :min="10"
                :max="300"
                placeholder="体重"
                style="width: 100%"
                @change="calculateBMI"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="住址" prop="address">
          <el-input v-model="patientForm.address" placeholder="请输入住址" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="紧急联系人" prop="emergencyContact">
              <el-input
                v-model="patientForm.emergencyContact"
                placeholder="紧急联系人"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人电话" prop="emergencyPhone">
              <el-input
                v-model="patientForm.emergencyPhone"
                placeholder="联系人电话"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="既往病史">
          <el-select
            v-model="patientForm.medicalHistory"
            multiple
            filterable
            allow-create
            placeholder="请选择或输入既往病史"
            style="width: 100%"
          >
            <el-option label="高血压" value="高血压" />
            <el-option label="糖尿病" value="糖尿病" />
            <el-option label="心脏病" value="心脏病" />
            <el-option label="肝炎" value="肝炎" />
            <el-option label="肾病" value="肾病" />
          </el-select>
        </el-form-item>

        <el-form-item label="过敏史">
          <el-select
            v-model="patientForm.allergies"
            multiple
            filterable
            allow-create
            placeholder="请选择或输入过敏史"
            style="width: 100%"
          >
            <el-option label="青霉素" value="青霉素" />
            <el-option label="链霉素" value="链霉素" />
            <el-option label="磺胺类" value="磺胺类" />
            <el-option label="阿司匹林" value="阿司匹林" />
          </el-select>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="patientForm.notes"
            type="textarea"
            :rows="3"
            placeholder="其他备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="loading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 患者详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="患者详情" width="900px">
      <div v-if="currentPatient" class="patient-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="患者编号">{{
            currentPatient.id
          }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{
            currentPatient.name
          }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{
            currentPatient.gender
          }}</el-descriptions-item>
          <el-descriptions-item label="年龄"
            >{{ currentPatient.age }}岁</el-descriptions-item
          >
          <el-descriptions-item label="血型">{{
            currentPatient.bloodType
          }}</el-descriptions-item>
          <el-descriptions-item label="BMI">{{
            currentPatient.bmi
          }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{
            currentPatient.phone
          }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{
            currentPatient.idCard
          }}</el-descriptions-item>
          <el-descriptions-item label="住址" :span="2">{{
            currentPatient.address
          }}</el-descriptions-item>
          <el-descriptions-item label="紧急联系人">{{
            currentPatient.emergencyContact
          }}</el-descriptions-item>
          <el-descriptions-item label="联系人电话">{{
            currentPatient.emergencyPhone
          }}</el-descriptions-item>
          <el-descriptions-item label="注册日期">{{
            currentPatient.registrationDate
          }}</el-descriptions-item>
          <el-descriptions-item label="最近就诊">{{
            currentPatient.lastVisit
          }}</el-descriptions-item>
          <el-descriptions-item label="既往病史" :span="2">
            <el-tag
              v-for="history in currentPatient.medicalHistory"
              :key="history"
              size="small"
              class="history-tag"
            >
              {{ history }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="过敏史" :span="2">
            <el-tag
              v-for="allergy in currentPatient.allergies"
              :key="allergy"
              size="small"
              type="warning"
              class="history-tag"
            >
              {{ allergy }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="主要诊断" :span="2">
            <el-tag
              v-for="diagnosis in currentPatient.diagnoses"
              :key="diagnosis"
              size="small"
              type="danger"
              class="history-tag"
            >
              {{ diagnosis }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{
            currentPatient.notes
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Download, Search, ArrowDown } from "@element-plus/icons-vue";
import { usePatientStore, type Patient } from "@/stores/modules/patient";

const patientStore = usePatientStore();

// 响应式数据
const searchQuery = ref("");
const filterStatus = ref("");
const filterGender = ref("");
const currentPage = ref(1);
const pageSize = ref(20);
const showAddDialog = ref(false);
const showDetailDialog = ref(false);
const editingPatient = ref<Patient | null>(null);
const selectedPatients = ref<Patient[]>([]);
const loading = ref(false);

// 表单相关
const formRef = ref();
const patientForm = ref({
  name: "",
  gender: "男" as "男" | "女",
  age: 0,
  phone: "",
  idCard: "",
  address: "",
  emergencyContact: "",
  emergencyPhone: "",
  medicalHistory: [] as string[],
  allergies: [] as string[],
  bloodType: "",
  height: 0,
  weight: 0,
  bmi: 0,
  status: "正常" as "正常" | "住院" | "出院" | "死亡",
  doctorId: "",
  departmentId: "",
  diagnoses: [] as string[],
  medications: [] as string[],
  notes: "",
  lastVisit: "",
});

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: "请输入患者姓名", trigger: "blur" },
    { min: 2, max: 20, message: "姓名长度在2到20个字符", trigger: "blur" },
  ],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  age: [
    { required: true, message: "请输入年龄", trigger: "blur" },
    {
      type: "number",
      min: 0,
      max: 150,
      message: "年龄必须在0到150之间",
      trigger: "blur",
    },
  ],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  idCard: [
    { required: true, message: "请输入身份证号", trigger: "blur" },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "请输入正确的身份证号",
      trigger: "blur",
    },
  ],
};

// 计算属性
const filteredPatients = computed(() => {
  let result = patientStore.patients;

  if (searchQuery.value) {
    result = patientStore.searchPatients(searchQuery.value);
  }

  if (filterStatus.value) {
    result = result.filter((p) => p.status === filterStatus.value);
  }

  if (filterGender.value) {
    result = result.filter((p) => p.gender === filterGender.value);
  }

  return result;
});

const currentPatient = computed(() => patientStore.currentPatient);
const patientStats = computed(() => patientStore.getPatientStats());

// 方法
const handleSearch = async () => {
  currentPage.value = 1;
  if (searchQuery.value.trim()) {
    await patientStore.searchPatientsWithApi(searchQuery.value);
  } else {
    await patientStore.getPatients();
  }
};

const handleFilter = () => {
  currentPage.value = 1;
};

const handleSelectionChange = (selection: Patient[]) => {
  selectedPatients.value = selection;
};

const handleRowClick = (row: Patient) => {
  patientStore.currentPatient = row;
};

const handleViewDetail = (patient: Patient) => {
  patientStore.currentPatient = patient;
  showDetailDialog.value = true;
};

const handleEdit = (patient: Patient) => {
  editingPatient.value = patient;
  Object.assign(patientForm.value, patient);
  showAddDialog.value = true;
};

const handleViewHistory = (patient: Patient) => {
  // 跳转到病历页面
  ElMessage.info("跳转到病历管理页面");
};

const handleAppointment = (patient: Patient) => {
  // 跳转到预约页面
  ElMessage.info("跳转到预约管理页面");
};

const handleMoreActions = async (command: string, patient: Patient) => {
  if (command === "delete") {
    try {
      await ElMessageBox.confirm(
        `确定要删除患者"${patient.name}"吗？`,
        "确认删除",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      );

      await patientStore.deletePatient(patient.id);
      ElMessage.success("删除成功");
    } catch (error) {
      if (error !== "cancel") {
        ElMessage.error("删除失败");
      }
    }
  } else if (command === "archive") {
    ElMessage.info("归档功能待开发");
  }
};

const calculateBMI = () => {
  if (patientForm.value.height && patientForm.value.weight) {
    patientForm.value.bmi = patientStore.calculateBMI(
      patientForm.value.height,
      patientForm.value.weight
    );
  }
};

const handleSave = async () => {
  try {
    await formRef.value.validate();

    calculateBMI();

    if (editingPatient.value) {
      await patientStore.updatePatient(
        editingPatient.value.id,
        patientForm.value
      );
      ElMessage.success("更新成功");
    } else {
      await patientStore.addPatient(patientForm.value);
      ElMessage.success("添加成功");
    }

    showAddDialog.value = false;
    resetForm();
  } catch (error) {
    console.error("保存失败:", error);
  }
};

const resetForm = () => {
  editingPatient.value = null;
  formRef.value?.resetFields();
  Object.assign(patientForm.value, {
    name: "",
    gender: "男",
    age: 0,
    phone: "",
    idCard: "",
    address: "",
    emergencyContact: "",
    emergencyPhone: "",
    medicalHistory: [],
    allergies: [],
    bloodType: "",
    height: 0,
    weight: 0,
    bmi: 0,
    status: "正常",
    doctorId: "",
    departmentId: "",
    diagnoses: [],
    medications: [],
    notes: "",
    lastVisit: "",
  });
};

const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
};

const handleCurrentChange = (page: number) => {
  currentPage.value = page;
};

const exportPatients = () => {
  ElMessage.info("导出功能待开发");
};

const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    正常: "success",
    住院: "warning",
    出院: "info",
    死亡: "danger",
  };
  return typeMap[status] || "info";
};

onMounted(async () => {
  await patientStore.getPatients();
});
</script>

<style lang="scss" scoped>
.patient-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }

  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.search-card {
  margin-bottom: 20px;

  .stats-info {
    display: flex;
    align-items: center;
    gap: 20px;

    .stat-item {
      font-size: 14px;
      color: #666;

      strong {
        color: #409eff;
        margin-left: 4px;
      }
    }
  }
}

.diagnosis-tag,
.history-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}

.more-diagnoses {
  font-size: 12px;
  color: #999;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.patient-detail {
  .history-tag {
    margin-right: 8px;
    margin-bottom: 4px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;

    .header-actions {
      width: 100%;
      justify-content: center;
    }
  }

  .search-card {
    :deep(.el-row) {
      .el-col {
        margin-bottom: 12px;
      }
    }
  }
}
</style>
